package com.utils.commons;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.utils.Employee;

/**
 * 登录用户工具类
 * HttpSession工具类
 * @author Administrator
 *
 */
public class LoginContextUtils {

	public static final String LOGIN_USER = "loginUser";

	public static void setLoginUser(Employee emp, HttpSession session) {
		session.setAttribute(LOGIN_USER, emp);
	}
	
	public static Employee getLoginUser(HttpSession session) {
		return (Employee) session.getAttribute(LOGIN_USER);
	}

	public static Employee getLoginUser() {
		return (Employee) getsession().getAttribute(LOGIN_USER);
	}

	public static HttpSession getsession() {
		return getRequest().getSession();
	}
	
	public static String getIP() {
		HttpServletRequest request = getRequest();
        String ip = request.getHeader("x-forwarded-for"); 
        if (!ObjectUtils.isEmpty(ip) && !"unknown".equalsIgnoreCase(ip)) {  
            // 多次反向代理后会有多个ip值，第一个ip才是真实ip
            if( ip.indexOf(",")!=-1 ){
                ip = ip.split(",")[0];
            }
        }  
        if (ObjectUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("Proxy-Client-IP");  
        }  
        if (ObjectUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("WL-Proxy-Client-IP");  
        }  
        if (ObjectUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("HTTP_CLIENT_IP");  
        }  
        if (ObjectUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");  
        }  
        if (ObjectUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getHeader("X-Real-IP");  
        }  
        if (ObjectUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {  
            ip = request.getRemoteAddr();  
        } 
        return ip;  
    }

	public static HttpServletRequest getRequest() {
		ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = requestAttributes.getRequest();
		return request;
	}
}
